<!--
 * @Descripttion:
 * @version:
 * @Editor: E-CHOOSEUS R&D
 * @LastEditors: E-CHOOSEUS R&D
-->
<template>
  <div class="index">
    <div class="act-bar">
      <el-date-picker
        v-model="datetimeRange"
        class="left"
        type="datetimerange"
        format="yyyy-MM-dd HH:mm"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :clearable="false"
        value-format="yyyy-MM-dd HH:mm:ss"
        @change="initData"
      >
      </el-date-picker>
      <img
        class="refresh left ml-10"
        src="@/assets/images/refresh.png"
        @click="initData"
      />
      <el-button
        v-has="'nursingDoc:edit'"
        class="my-btn"
        type="success"
        @click="add"
        >新 增</el-button
      >
      <el-button
        v-has="'nursingDoc:edit'"
        class="my-btn"
        type="primary"
        @click="beforeSave"
        >保 存</el-button
      >
      <el-button
        v-has="'nursingDoc:export'"
        class="my-btn"
        :loading="isExporting"
        @click="handleOutput"
      >
        导 出
      </el-button>
      <el-button v-has="'nursingDoc:export'" class="my-btn" @click="print"
        >打 印</el-button
      >
      <button
        v-show="false"
        ref="printBtn"
        v-has="'nursingDoc:export'"
        v-print="printConf"
        class="my-btn"
      >
        打 印
      </button>
    </div>
    <div class="multi-container">
      <div id="printDom" v-loading="loading" class="printMain">
        <div
          v-for="(item, index) in pages"
          :key="index"
          :ref="e => (printDomRefs[index] = e)"
          class="doc-container"
          :class="'doc-container' + index"
        >
          <i
            v-show="index > 0 && !isPrinting && !isExporting"
            class="remove-icon el-icon-close"
            @click="remove(index, item)"
          ></i>
          <DocHeader
            ref="docHeaderRef"
            :title="getTitle()"
            :bottomBorder="false"
            diagnosis
          />
          <mainPage
            :ref="e => (formRef[index] = e)"
            :data="item"
            :error-time="errorTime"
            :page-index="index"
            @update="initData"
          />
        </div>
      </div>
    </div>
    <div class="pagination">
      <div
        v-for="(item, index) in pages"
        :key="index"
        class="item"
        @click="handlePageIntoView(index)"
      >
        {{ index + 1 }}
      </div>
    </div>
  </div>
</template>

<script>
import { format } from 'date-fns'
import { cloneDeep } from 'lodash-unified'
import {
  computed,
  defineComponent,
  nextTick,
  reactive,
  toRefs,
  watch
} from 'vue'
import { useRouter } from 'vue-router/composables'

import { Doc } from '@/api/doc'
import {
  getElementFnFromInstance,
  getStoreFromInstance
} from '@/utils/instance'

import { useDocExport } from '../../hooks'
import DocHeader from '../DocHeader.vue'
import mainPage from './mainPage.vue'

export default defineComponent({
  name: 'BloodOxygenTest',
  components: { mainPage, DocHeader },
  props: {
    data: {
      type: Object,
      default: () => {}
    }
  },
  setup(props) {
    const state = reactive({
      printConf: {
        id: 'printDom',
        popTitle: '打印', // 打印配置页上方标题
        extraHead: '', //最上方的头部文字，附加在head标签上的额外标签,使用逗号分隔
        preview: '', // 是否启动预览模式，默认是false（开启预览模式，可以先预览后打印）
        previewTitle: '', // 打印预览的标题（开启预览模式后出现）,
        previewPrintBtnLabel: '', // 打印预览的标题的下方按钮文本，点击可进入打印（开启预览模式后出现）
        zIndex: '', // 预览的窗口的z-index，默认是 20002（此值要高一些，这涉及到预览模式是否显示在最上面）
        previewBeforeOpenCallback() {}, //预览窗口打开之前的callback（开启预览模式调用）
        previewOpenCallback() {}, // 预览窗口打开之后的callback（开启预览模式调用）
        beforeOpenCallback() {}, // 开启打印前的回调事件
        openCallback() {}, // 调用打印之后的回调事件
        closeCallback(vue) {
          vue.isPrinting = false
        }, //关闭打印的回调事件（无法确定点击的是确认还是取消）
        url: '',
        standard: '',
        extraCss: ''
      },
      loading: false, //加载中
      pages: [], //表格数据
      isPrinting: false,
      isExporting: false,
      form: {},
      recordData: [],
      printBtn: {},
      printDomRefs: [],
      docHeaderRef: {},
      formRef: [],
      pageNum: 54,
      errorTime: [],
      datetimeRange: []
    })

    const { handleDocExportMulti } = useDocExport()
    const store = getStoreFromInstance()
    const { $confirm, $message } = getElementFnFromInstance()
    const router = useRouter()

    const patCur = computed(() => store.getters.patCur)
    const user = computed(() => store.getters.user)

    const isHistory = computed(() => store.getters.isHistory)

    async function initData() {
      state.loading = true
      if (!patCur.value) {
        return
      }
      if (
        !state.datetimeRange ||
        !state.datetimeRange[0] ||
        !state.datetimeRange[1]
      ) {
        initDatetimeRange()
      }
      const params = {
        hospitalNumber: patCur.value.hospitalNumber,
        startTime: +new Date(state.datetimeRange[0]),
        endTime: +new Date(state.datetimeRange[1])
      }
      const { data: tableData } = await Doc.getBSList(params)
      state.pages.length = 0
      const len = tableData.length
      if (len == 0) {
        state.recordData = []
        const arr = []
        for (let x = 0; x < state.pageNum; x++) {
          arr.push({
            date: null,
            timePoint: null,
            value: '',
            zxr: '',
            hdr: '',
            remark: ''
          })
        }
        state.pages.push(arr)
      } else {
        const recordData = tableData.map(item => {
          if (item.date && item.timePoint) {
            item.date = Number(item.date)
            item.value = Number(item.value)
            item.timePoint = Number(item.timePoint)
            const createTime = new Date(
              format(item.date, 'yyyy-MM-dd') +
                ' ' +
                format(item.timePoint, 'HH:mm:ss')
            )
            return {
              id: '',
              createTime: createTime,
              showValue: '',
              createdBy: ''
            }
          }
          return ''
        })
        state.recordData = recordData.filter(item => !!item)

        for (let i = 0; i < tableData.length; i = i + state.pageNum) {
          const arr = tableData.slice(i, state.pageNum + i)
          if (arr.length < state.pageNum) {
            const remainNum = state.pageNum - arr.length
            for (let x = 0; x < remainNum; x++) {
              arr.push({
                date: null,
                timePoint: null,
                value: '',
                zxr: '',
                hdr: '',
                remark: '',
                bedNumber: patCur.value.bedNumber,
                patientIdent: patCur.value.patientIdent,
                patientName: patCur.value.patientName
              })
            }
          }
          state.pages.push(arr)
        }
      }

      state.loading = false
    }

    function add() {
      const arr = []
      for (let x = 0; x < state.pageNum; x++) {
        arr.push({
          date: null,
          timePoint: null,
          value: '',
          zxr: '',
          hdr: '',
          remark: '',
          bedNumber: patCur.value.bedNumber,
          patientIdent: patCur.value.patientIdent,
          patientName: patCur.value.patientName
        })
      }
      state.pages.push(arr)

      nextTick(() => {
        const wrapper = document.querySelector('.multi-container')
        const items = document.querySelectorAll('.doc-container')
        const lastItem = items[items.length - 1]
        wrapper.scroll({
          top: lastItem.offsetTop - 82,
          behavior: 'smooth'
        })
      })
    }

    async function beforeSave() {
      const arr = []
      let isError = false
      for (const formRef of state.formRef) {
        const tableData = cloneDeep(formRef.getParams()).filter(
          res => res.date || res.timePoint || res.value || res.zxr || res.hdr
        )
        tableData.map(res => {
          if (!res.zxr) {
            res.zxr = user.value.name
          }
          delete res.id
          if (res.date && res.timePoint && res.value) {
            res.time = +new Date(
              format(res.date, 'yyyy-MM-dd') +
                ' ' +
                formatTimePoint(res.timePoint) +
                ':00'
            )
          } else {
            isError = true
            return
          }
        })
        if (isError) {
          $message.error('请填写完整后进行保存！')
          return
        }
        arr.push(...tableData)
      }
      save(arr)
    }
    function formatTimePoint(time) {
      if (typeof time == 'number') {
        const date = new Date(time)
        return `${date.getHours()}:${date.getMinutes()}`
      } else {
        return time
      }
    }

    function save(list) {
      // 修改
      Doc.editBSList({
        hospitalNumber: patCur.value.hospitalNumber,
        list
      }).then(({ data: res }) => {
        if (res.resultType == 1) {
          if (state.errorTime.length > 0) {
            state.errorTime = []
          }
          $message.success(`保存成功`)
          state.datetimeRange = [
            state.datetimeRange[0],
            format(+new Date(), 'yyyy-MM-dd HH:mm:ss')
          ]
        } else if (res.resultType == 2) {
          state.errorTime.length = 0
          $message.error('此时间下已有血糖记录，请重新填写')
          res.list.map(item => {
            if (item.resultType == 2) {
              const time = +new Date(
                format(item.date * 1, 'yyyy-MM-dd') +
                  ' ' +
                  formatTimePoint(item.timePoint * 1) +
                  ':00'
              )
              if (!state.errorTime.includes(time)) {
                state.errorTime.push(time)
              }
            }
          })
        }
      })
    }

    function returnDom() {
      return state.printDomRefs
    }

    function handleOutput() {
      // this.loading = true;
      state.isExporting = true
      setTimeout(() => {
        handleDocExportMulti(
          state.printDomRefs,
          '',
          props.data.title + '.pdf',
          () => {
            state.isExporting = false
          }
        )
      }, 500)
    }

    function print() {
      state.isPrinting = true
      nextTick(() => {
        state.printBtn.click()
      })
    }

    function remove(index, item) {
      const isAdd = item.filter(res => res.id).length == 0
      $confirm('是否删除此页？')
        .then(() => {
          state.pages.splice(index, 1)

          // 删除非新增项时执行保存操作
          if (!isAdd) {
            nextTick(() => {
              beforeSave()
            })
          }
        })
        .catch(() => {})
    }

    function getTitle() {
      return `<span style="padding-left: 130px;"></span>${props.data.title}<span style="font-size: 16px;font-weight: 500">（单位：mmol/L）</span>`
    }

    function handlePageIntoView(index) {
      document.querySelector('.doc-container' + index)?.scrollIntoView()
    }

    function initDatetimeRange() {
      let startTime = +new Date(),
        endTime = +new Date()
      if (patCur.value.ryInfo?.ryDate) {
        startTime = patCur.value.ryInfo.ryDate
      }
      if (patCur.value.endCkTime) {
        endTime = patCur.value.endCkTime
      }
      state.datetimeRange = [
        format(startTime, 'yyyy-MM-dd HH:mm:ss'),
        format(endTime, 'yyyy-MM-dd HH:mm:ss')
      ]
    }

    watch(
      patCur,
      val => {
        if (val) {
          initDatetimeRange()
        }
        initData()
      },
      { immediate: true }
    )

    return {
      ...toRefs(state),
      beforeSave,
      initData,
      add,
      returnDom,
      handleOutput,
      print,
      remove,
      getTitle,
      handlePageIntoView
    }
  }
})
</script>

<style lang="scss" scoped>
.index {
  height: calc(100% - 15px);
}

.act-bar {
  min-height: 52px;
  margin-bottom: 10px;
  padding: 9px 10px;
  text-align: right;
  border-bottom: 1px solid #f2f4f5;
}

.multi-container {
  height: calc(100% - 100px);
  padding-bottom: 20px;
  overflow-y: auto;
}

.printMain {
  width: 840px;
  margin: 0 auto;
}

.doc-container {
  position: relative;
  margin: 0 auto;
  width: 840px;
  height: 1188px;
  background-color: #fff;
  border: 1px solid #f0f0f0;
  padding: 20px;

  .remove-icon {
    position: absolute;
    top: 20px;
    right: 20px;
    font-size: 22px;
    font-weight: bold;
    color: red;
    cursor: pointer;
  }
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;

  .item {
    width: 32px;
    height: 32px;
    border-radius: 2px;
    margin: 0 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 13px;
    background-color: #f4f4f5;
    color: #606266;
    cursor: pointer;
  }
}

.pageNum {
  margin-top: 18px;
  margin-bottom: 15px;
}

.refresh {
  width: 32px;
  padding: 8px;
  background: #155ef3;
  border-radius: 4px;
  cursor: pointer;
  vertical-align: top;
}
</style>
